package com.kuanter.kuanterauto.activity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.RechargeActivity.SelecterGradePopupWindow.PopInsuranceAdapter;
import com.kuanter.kuanterauto.adapter.CardAndNumberImageAdapter;
import com.kuanter.kuanterauto.alipay.AlipayCenter;
import com.kuanter.kuanterauto.alipay.AlixId;
import com.kuanter.kuanterauto.alipay.BaseHelper;
import com.kuanter.kuanterauto.alipay.OrderInfoUtil;
import com.kuanter.kuanterauto.alipay.ResultChecker;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.CardInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.kuanter.kuanterauto.utils.Utility;
import com.kuanter.kuanterauto.view.MyGallery;
import com.kuanter.kuanterauto.wapalipay.WapPayActivity;
import com.unionpay.UPPayAssistEx;

public class ConfirmRechargeJinEActivity extends BaseActivity_NoBar implements Callback {
	private Intent intentCome; 
	private String recharge_style;
	private List<String> strCredits = new ArrayList<String>();
	public View inputView;
	public EditText input_jine_et;
	private TextView choosed_credits_tv;
	private SelecterGradePopupWindow menuWindow;
	private AlipayCenter alipayCenter;
	private boolean isPrepare;
	private DataLoader dataLoader;
	private Intent intent = new Intent();
	private boolean isCheckForPartnerAndSeller;
	private Activity activity;
	public static boolean isChargeSuccess = false ;
	
	private ProgressDialog mLoadingDialog = null;
	private Handler mHandler = null;
	
	/*****************************************************************
     * mMode参数解释：
     *      "00" - 启动银联正式环境
     *      "01" - 连接银联测试环境
     *****************************************************************/
    private String mMode = "01";
    private static final String TN_URL_01 = "http://222.66.233.198:8080/sim/gettn";
    private static final int PLUGIN_VALID = 0;
    private static final int PLUGIN_NOT_INSTALLED = -1;
    private static final int PLUGIN_NEED_UPGRADE = 2;
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(myBroadcastReceiver != null){
			unregisterReceiver(myBroadcastReceiver);
		}
	}
	// 这里接收支付结果，支付宝手机端同步通知
			private Handler mHandlerAlipay = new Handler() {
				public void handleMessage(Message msg) {
					try {
						String strRet = (String) msg.obj;

						Log.e("wuyang", strRet); // strRet范例：resultStatus={9000};memo={};result={partner="2088201564809153"&seller="2088201564809153"&out_trade_no="050917083121576"&subject="123456"&body="2010新款NIKE 耐克902第三代板鞋 耐克男女鞋 386201 白红"&total_fee="0.01"&notify_url="http://notify.java.jpxx.org/index.jsp"&success="true"&sign_type="RSA"&sign="d9pdkfy75G997NiPS1yZoYNCmtRbdOP0usZIMmKCCMVqbSG1P44ohvqMYRztrB6ErgEecIiPj9UldV5nSy9CrBVjV54rBGoT6VSUF/ufjJeCSuL510JwaRpHtRPeURS1LXnSrbwtdkDOktXubQKnIMg2W0PreT1mRXDSaeEECzc="}
						switch (msg.what) {
						case AlixId.RQF_PAY: {
							//
							alipayCenter.closeProgress();

							BaseHelper.log("wuyang", strRet);

							// 处理交易结果
							try {
								// 获取交易状态码，具体状态代码请参看文档
								String tradeStatus = "resultStatus={";// 无多大意义
								int imemoStart = strRet.indexOf("resultStatus=");
								imemoStart += tradeStatus.length();
								int imemoEnd = strRet.indexOf("};memo=");
								tradeStatus = strRet.substring(imemoStart, imemoEnd);

								// 先验签通知
								ResultChecker resultChecker = new ResultChecker(strRet);
								int retVal = resultChecker.checkSign();
//								boolean retVal = com.kuanter.kuanterauto.alipay.Result.checkSign(strRet);
								// 验签失败
								if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
//								if (!retVal) {
									BaseHelper.showDialog(
											activity,
											"提示",
											getResources().getString(
													R.string.check_sign_failed),
											android.R.drawable.ic_dialog_alert);
								} else {// 验签成功。验签成功后再判断交易状态码
									if (tradeStatus.equals("9000")){// 判断交易状态码，只有9000表示交易成功
										ProApplication.getInstance().setCardInfoList(null);
										BaseHelper.showDialog(activity, "提示",
												"支付成功",
												R.drawable.infoicon);
										Intent data = new Intent();
//										data.putExtra("chooseed_credits", chooseed_credits);
										setResult(255, data );
									}else{
										BaseHelper.showDialog(activity, "提示",
												"支付失败",
												R.drawable.infoicon);
									}
										
								}

							} catch (Exception e) {
								e.printStackTrace();
								BaseHelper.showDialog(activity, "提示", "取消",
										R.drawable.infoicon);
							}
						}
							break;
						}

						super.handleMessage(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
	
	Handler handlerRechargeAPP = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;//{"orderNo":"CZ20130524155046","status":true}
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
															// 字段值是否为false
							com.alibaba.fastjson.JSONObject jsonObjectResult = JSON
									.parseObject(result);
							String orderNo = jsonObjectResult.getString("orderNo");
							//intentCome.getStringExtra(Recharge2Activity.XuNiAccountCardNumber)
//							String orderInfo = OrderInfoUtil.getOrderInfo(orderNo, "宽途卡充值","宽途汽车",choosed_credits_tv.getText().toString());
							String orderInfo = OrderInfoUtil.getNewOrderInfo(orderNo, "宽途卡充值","宽途汽车",choosed_credits_tv.getText().toString());
							boolean payResult = alipayCenter.payStart(orderInfo, mHandlerAlipay);
							if(payResult){
								CardAndAccountActivity.flag = 200;
							}else {
								CardAndAccountActivity.flag = 0;
							}
							finishProgress();
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
//							showToast("失败");
							showToast("网络错误,请稍后再试!");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private MyBroadcastReceiver myBroadcastReceiver;
	
	//自定义广播
		private class MyBroadcastReceiver extends BroadcastReceiver{

			@Override
			public void onReceive(Context context, Intent intent) {
				InputMethodManager m = (InputMethodManager)
						ConfirmRechargeJinEActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
	                            m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}
			
		}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.confirm_recharge_jin_e);
		mHandler = new Handler(this);
		
		activity = this;
		//注册广播
				IntentFilter filter = new IntentFilter("input");
				myBroadcastReceiver = new MyBroadcastReceiver();
				registerReceiver(myBroadcastReceiver, filter );
				///////////////////////////
		choosed_credits_tv = (TextView) this.findViewById(R.id.choosed_credits_tv);
		intentCome = getIntent();
		recharge_style = intentCome.getStringExtra(Recharge2Activity.RECHARGE_KIND);
		strCredits.add("0.01");
		strCredits.add("100");
		strCredits.add("200");
		strCredits.add("500");
		strCredits.add("其他金额");
		menuWindow = new SelecterGradePopupWindow(ConfirmRechargeJinEActivity.this, new MyPopListViewClick(),strCredits);
	}
	public void back(View v){
		finish();
	}
	public void comfirmRecharge(View v){
		isChargeSuccess = true;
		if(ProApplication.getInstance().getCardInfoList() != null && ProApplication.getInstance().getCardInfoList().size() > 0){
			ProApplication.getInstance().getCardInfoList().clear();
		}
		SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
		if(Recharge2Activity.RECHARGE_KIND_APP.equals(recharge_style)){
			// 调用支付接口,支付成功通知服务器页面，支付成功，并将积分设置
			//参数名：cardNumber,rechargeAmount,mobileNumber
				alipayCenter = new AlipayCenter(this); 
				isPrepare = alipayCenter.payPrepareForcheckInstallAlipay();
				if (isPrepare) {
					isCheckForPartnerAndSeller = alipayCenter.checkInfoForPartnerAndSeller();
					if (isCheckForPartnerAndSeller) {
						dataLoader = new DataLoader(this);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("cardNumber",intentCome.getStringExtra(Recharge2Activity.XuNiAccountCardNumber)));
						params.add(new BasicNameValuePair("rechargeAmount",choosed_credits_tv.getText().toString()));
						params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
						params.add(new BasicNameValuePair("type", "0"));
						dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.ORDER, params, handlerRechargeAPP, "", false);
						showProgress("请稍等...");
				}
			}
			
		}else if(Recharge2Activity.RECHARGE_KIND_WAP.equals(recharge_style)){
			//cardRecharge/isExistVirtualCardNumber(String cardNumber, String mobileNumber)  //true打开
			showProgress("请稍等...");
			dataLoader = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cardNumber",intentCome.getStringExtra(Recharge2Activity.XuNiAccountCardNumber)));
			params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
			dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.isExistVirtualCardNumber, params, webHandler, "", false);
			
		} else if(Recharge2Activity.RECHARGE_KIND_UNIPAY.equals(recharge_style)) {
			//TODO  银联
			mLoadingDialog = ProgressDialog.show(ConfirmRechargeJinEActivity.this, // context 
                    "", // title 
                    "正在获取交易流水号,请稍候...", // message 
                    true);
			/************************************************* 
             * 
             *  步骤1：从网络开始,获取交易流水号即TN 
             *  
             ************************************************/
//            new Thread(getUnipayNo).start();
			dataLoader = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cardNumber",intentCome.getStringExtra(Recharge2Activity.XuNiAccountCardNumber)));
			params.add(new BasicNameValuePair("rechargeAmount",choosed_credits_tv.getText().toString()));
			params.add(new BasicNameValuePair("mobileNumber",sp.getString("mobileNumber", "-1")));
			params.add(new BasicNameValuePair("type", "1"));
			dataLoader.DisplayData(MainConstants.HOST_test+ HttpConfigAPI.ORDER, params, mHandler, "", false);
		}
	}
	
	public void rechargeJinE(View v){
		menuWindow.showAtLocation(ConfirmRechargeJinEActivity.this.findViewById(R.id.temp9), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
	}
	
	public class MyPopListViewClick implements OnItemClickListener {

		protected String chooseed_credits;

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
				
				if(strCredits.get(position).equals("其他金额")){
					inputView = View.inflate(ConfirmRechargeJinEActivity.this, R.layout.input_view, null);
					input_jine_et = (EditText)inputView.findViewById(R.id.input_jine_et);
					AlertDialog.Builder builder = new AlertDialog.Builder(ConfirmRechargeJinEActivity.this)
					.setView(inputView)
					.setMessage("请输入充值金额")
					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if(!input_jine_et.getText().toString().trim().equals("")){
								if(Integer.valueOf(input_jine_et.getText().toString().trim())>=50){
									chooseed_credits = input_jine_et.getText().toString();
									choosed_credits_tv.setText(input_jine_et.getText().toString());
								}else {
									showToast("最小充值金额为50元"); 
								}
							}else {
								showToast("请输入充值金额");
							}
						}
					}).setNegativeButton("取消", null);
					builder.create().show();
					//发送广播显示输入法
					Intent intent = new Intent("input");
					sendBroadcast(intent);
				}else{
					chooseed_credits = strCredits.get(position);
					choosed_credits_tv.setText(chooseed_credits);
				}
				menuWindow.dismiss();
			}
		}
	
	public class SelecterGradePopupWindow extends PopupWindow {


		private TextView btn_cancel;
		private View mMenuView;
		
		ListView insuranceview;
		LayoutInflater inflater;
		
		PopInsuranceAdapter adapter;
		
		List<String> ci_pop;

		public SelecterGradePopupWindow(Activity context,OnItemClickListener itemsOnClick,List<String> ci_pop) {
			super(context);
			this.ci_pop = ci_pop;
			
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mMenuView = inflater.inflate(R.layout.alert_dialog, null);
			btn_cancel = (TextView) mMenuView.findViewById(R.id.btn_cancel);
			//取消按钮
			btn_cancel.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					//销毁弹出框
					dismiss();
				}
			});
			
			insuranceview = (ListView) mMenuView.findViewById(R.id.insuranceview);
			insuranceview.setOnItemClickListener(itemsOnClick);
			
			adapter = new PopInsuranceAdapter();
			insuranceview.setAdapter(adapter);
			Utility.setListViewHeightBasedOnChildren(insuranceview);
			
			//设置SelectPicPopupWindow的View
			this.setContentView(mMenuView);
			//设置SelectPicPopupWindow弹出窗体的宽
			this.setWidth(LayoutParams.FILL_PARENT);
			//设置SelectPicPopupWindow弹出窗体的高
			this.setHeight(LayoutParams.WRAP_CONTENT);
			//设置SelectPicPopupWindow弹出窗体可点击
			this.setFocusable(true);
			//设置SelectPicPopupWindow弹出窗体动画效果
			this.setAnimationStyle(R.style.AnimBottom);
			//实例化一个ColorDrawable颜色为半透明
			ColorDrawable dw = new ColorDrawable(0xb0000000);
			//设置SelectPicPopupWindow弹出窗体的背景
			this.setBackgroundDrawable(dw);
			//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
			mMenuView.setOnTouchListener(new OnTouchListener() {
				
				public boolean onTouch(View v, MotionEvent event) {
					
					int height = mMenuView.findViewById(R.id.pop_layout).getTop();
					int y=(int) event.getY();
					if(event.getAction()==MotionEvent.ACTION_UP){
						if(y<height){
							dismiss();
						}
					}				
					return true;
				}
			});

		}
		class PopInsuranceAdapter extends BaseAdapter {
			@Override
			public int getCount() {
				return ci_pop == null ? 0 : ci_pop.size();
			}
			
			@Override
			public Object getItem(int arg0) {
				return ci_pop.get(arg0);
			}
			
			@Override
			public long getItemId(int arg0) {
				return arg0;
			}
			
			@Override
			public View getView(int position, View view, ViewGroup parent) {
				if(view == null) {
					view = inflater.inflate(R.layout.pop_insurance_item, null);
				}
				TextView item_insurance = (TextView) view.findViewById(R.id.item_insurance);
				item_insurance.setText(ci_pop.get(position));
				return view;
			}
			
		}
	}
	
	private Runnable getUnipayNo = new Runnable() {
		
		@Override
		public void run() {
			String tn = null;
	        InputStream is;
	        try {

	            String url = TN_URL_01;

	            URL myURL = new URL(url);
	            URLConnection ucon = myURL.openConnection();
	            ucon.setConnectTimeout(120000);
	            is = ucon.getInputStream();
	            int i = -1;
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            while ((i = is.read()) != -1) {
	                baos.write(i);
	            }

	            tn = baos.toString();
	            is.close();
	            baos.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	        Message msg = mHandler.obtainMessage();
	        msg.obj = tn;
	        mHandler.sendMessage(msg);
		}
	};
	
	@Override
	public boolean handleMessage(Message msg) {
		Log.e("aaa", " " + "" + msg.obj);
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        String pn = "";
        String json = (String) msg.obj;
        if(json != null) {
        	try {
				JSONObject jo = new JSONObject(json);
				if(StringUtils.isSuccess(json)) {
					pn = jo.optString("tradeNo");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
        }

        if (pn == null || (pn.length() == 0)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("错误提示");
            builder.setMessage("网络错误,请稍后再试!");
            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        } else {
            /************************************************* 
             * 
             *  步骤2：通过银联工具类启动支付插件 
             *  
             ************************************************/
            // mMode参数解释：
            // 0 - 启动银联正式环境
            // 1 - 连接银联测试环境
            int ret = UPPayAssistEx.startPay(this, null, null, pn, mMode);
            if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
                // 需要重新安装控件
                Log.e("aaa", " plugin not found or need upgrade!!!");
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("完成购买需要安装银联支付控件，是否安装？");
                builder.setNegativeButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.dismiss();
                                Intent intentPlug = new Intent(Intent.ACTION_VIEW);
                                intentPlug.setData(Uri.parse("http://mobile.unionpay.com/download/securepayplugin"));
                                startActivity(intentPlug);
                            }
                        });

                builder.setPositiveButton("取消",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();

            }
            Log.e("aaa", "" + ret);
        }
		return false;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/************************************************* 
         * 
         *  步骤3：处理银联手机支付控件返回的支付结果 
         *  
         ************************************************/
        if (data == null) {
            return;
        }

        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel
         *      分别代表支付成功，支付失败，支付取消
         */
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
        	CardAndAccountActivity.flag = 200;
            msg = "支付成功！";
            showToast(msg);
            finish();
        } else if (str.equalsIgnoreCase("fail")) {
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "支付失败,取消了支付";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("支付结果通知");
        builder.setMessage(msg);
        builder.setInverseBackgroundForced(true);
        //builder.setCustomTitle();
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private Handler webHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			finishProgress();
			String json = (String) msg.obj;
			if(json != null) {
				try {
					JSONObject jo = new JSONObject(json);
					if(StringUtils.isSuccess(json)) {
						String message = jo.optString("message");
						if(message.equals("true")) {
							SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
							// 调用支付接口,支付成功通知服务器页面，支付成功，并将积分设置
							//支付宝网页支付	方法名：cardRecharge/{cardNumber}/{rechargeAmount}/{mobileNumber}/trade		参数名：cardNumber，rechargeAmount，mobileNumber
							intent.putExtra("cardNumber", intentCome.getStringExtra(Recharge2Activity.XuNiAccountCardNumber));
							intent.putExtra("rechargeAmount", choosed_credits_tv.getText().toString());
							intent.putExtra("mobileNumber", sp.getString("mobileNumber", "-1"));
							intent.setClass(ConfirmRechargeJinEActivity.this, WapPayActivity.class);
							startActivity(intent);
							CardAndAccountActivity.flag = 200;		
						} else {
							showToast("网络错误,请稍后再试!");
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			super.handleMessage(msg);
		}
	};
}
